package com.java.stack;

/**
 * 单链表实现 栈
 *
 * @author 19252
 */
public class SingleLinkedListStackDemo {
    public static void main(String[] args) {
        SingleLinkedListStack stack = new SingleLinkedListStack(5);
        stack.showStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(6);
        System.out.println("============> 入栈 <===========");
        stack.showStack();
        stack.pop();
        stack.pop();
        stack.push(6);
        System.out.println("============> 出栈 <===========");
        stack.showStack();
        System.out.println("============> 出栈判空 <===========");
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
        stack.pop();
    }
}

/**
 * 单链表栈
 */
class SingleLinkedListStack {

    private int maxSize;

    private Node head = new Node();

    private int top = -1;

    public SingleLinkedListStack(int maxSize) {
        this.maxSize = maxSize;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public boolean isFull() {
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public void push(int value) {
        if (isFull()) {
            System.out.println("栈已满！");
            return;
        }
        Node temp = head;
        Node node = new Node(value);
        node.setNext(temp.getNext());
        temp.setNext(node);
        top++;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈中没有数据！");
        }
        Node temp = head;
        int value = temp.getNext().getValue();
        top--;
        temp.setNext(temp.getNext().getNext());
        return value;
    }

    public void showStack() {
        if (isEmpty()) {
            System.out.println("栈中没有数据！");
            return;
        }
        Node temp = head;
        for (int i = top; i >= 0; i--) {
            System.out.printf("sack[%d] = %d \n", i, temp.getNext().getValue());
            temp = temp.getNext();
        }
    }

}

class Node {
    private int value;

    private Node next;


    public Node() {
    }

    public Node(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}
